import mysql.connector
from mysql.connector import Error
from typing import Optional, List, Dict, Any

class DatabaseManager:
    def __init__(self, host="localhost", user="root", password="123456", database="well_data"):
        self.host=host
        self.user=user
        self.password=password
        self.database=database
    
    def connect(self):
        try:
            self.connection=mysql.connector.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )
            print("数据库连接成功")
        except Error as e:
            print(f"数据库连接失败: {e}")
            
    #查询数据
    def query_data(self, query: str, params: tuple = None) -> List[Dict[str, Any]]:
        try:
            self.connect()
            cursor=self.connection.cursor(dictionary=True)
            cursor.execute(query, params)#解释:cursor.execute()是cursor类的一个方法，用于执行一个查询。
            result=cursor.fetchall()#解释:fetchall()是cursor类的一个方法，用于获取查询结果。
        except Error as e:
            print(f"查询失败: {e}")
            return []
        
    def query_update(self,query:str,params:tuple=None):
        self.connect()
        cursor=self.connection.cursor()
        try:
            cursor.execute(query,params)
            self.connection.commit()#解释:commit()是connection类的一个方法，用于提交事务。
            print("更新成功")
        except Error as e:
            print(f"更新失败: {e}")
        finally:
            cursor.close()
            
    def close(self):
        """关闭数据库连接"""
        if self.connection and self.connection.is_connected():
            self.connection.close()
            print("数据库连接已关闭")
